package blue.datacenter;

import java.nio.charset.Charset;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class SlaveConn implements ConnectionInterface {
	// TODO
	private SocketChannel sock_channel_;
	private int id_;
	private String ip_;
	private int port_;
	private Object attach_obj_;
	//private ByteBuffer buff_; 
	private ConnectionType type_;
	
	public SlaveConn(SocketChannel sock_channel){
		ip_ = sock_channel.socket().getInetAddress().getHostAddress();
		port_ = 0;
		sock_channel_ = sock_channel;
		//buff_ = ByteBuffer.allocate(512);
		type_ = ConnectionType.SlaveConn;
	}

	@Override
	public void setTypePrivilege() {
		type_ = ConnectionType.PrivilegeSlaveConn;
	}
	
	@Override
	public SocketChannel getSockChannel() {
		return sock_channel_;
	}

	@Override
	public String getIP() {
		return ip_;
	}

	@Override
	public int getPort() {
		return port_;
	}

	@Override
	public String getSN() {
		return ip_+":"+port_;
	}

	@Override
	public String read() throws IOException {
	    ByteBuffer recv_buf = ByteBuffer.allocate(512);
	    int recv_cnt = sock_channel_.read(recv_buf);
	    if (recv_cnt<0) return null;
	    recv_buf.flip();
	    byte[] recv_bytes=new byte[recv_cnt];
	    recv_buf.get(recv_bytes, 0, recv_cnt);
	    
		return new String(recv_bytes,Charset.forName("UTF-8"));
	}

	@Override
	public int write(String msg) throws IOException {
	    byte[] bytes = msg.getBytes( Charset.forName("UTF-8" ));
		ByteBuffer send_buf = ByteBuffer.allocate(512);
		//send_buf.clear();
		send_buf.put(bytes);
		send_buf.flip();
		return sock_channel_.write(send_buf);
	}

	@Override
	public ConnectionType getType() {
		return type_;
	}

	@Override
	public boolean reconnection() {
		return false;
	}

	@Override
	public void setId(int id) {
		id_ = id;
	}
	
	@Override
	public int getId() {
		return id_;
	}

	@Override
	public void setAttach(Object obj){ attach_obj_ = obj; }

	@Override
	public Object getAttach(){ return attach_obj_;}

}
